import hashlib
import base64
import hmac
import json
import time

import requests

# 飞书的webhook地址以及webhook的secret
webhook = 'https://open.feishu.cn/open-apis/bot/v2/hook/cf183033-f935-4654-959e-f98b1560bc8f'
secret = 'mUYYDnK0c6QDxujdQB3yWg'

# 定义请求头
headers = {
    'Content-Type': 'application/json'
}


# 生成签名
def gen_sign(timestamp, secret):
    # 拼接timestamp和secret
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
    # 对结果进行base64处理
    sign = base64.b64encode(hmac_code).decode('utf-8')
    return sign


# 请求体
def wrap_data(text):
    current_timestamp = int(time.time())
    print(f"当前时间戳（单位为秒）：{current_timestamp}")
    sign = gen_sign(current_timestamp, secret)
    # 定义请求体
    return {
        'msg_type': 'text',
        'sign': sign,
        'content': {
            'text': text
        }
    }


def send_msg(text):
    data = wrap_data(text)
    # 将字典转换为JSON字符串
    payload = json.dumps(data)

    # 发送POST请求
    response = requests.post(webhook, data=payload, headers=headers)
    print(f'response:{response}')


send_msg("request example")
